/**
 * @作者 zw
 * @微信公号 搬砖暗夜码农
 * @开源项目 $ https://gitee.com/zhouwei5208888/spring-boot-distributed
 * @我的博客 $ http://itzhouwei.com
 * @创建时间 2025/1/20 10:32
 */
package com.itzhouwei.datasource.dynamic.util;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itzhouwei.datasource.dynamic.domain.entity.TestDbInfo;
import com.itzhouwei.datasource.dynamic.domain.po.DataSourceEntity;
import com.itzhouwei.datasource.dynamic.mapper.TestDbInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName：LoadDataSourceRunner
 * @Author: zw，微信公共号：搬砖暗夜码农
 * @Date: 2025/1/20 10:32
 * @Description:
 * @Copyright：公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、学习、分享、成长，让自己和他人都能有所收获！
 */
@Component
public class LoadDataSourceRunner implements CommandLineRunner {
    @Resource
    private DynamicDataSource dynamicDataSource;
    @Resource
    private TestDbInfoMapper testDbInfoMapper;
    @Override
    public void run(String... args) throws Exception {
        List<TestDbInfo> testDbInfos = testDbInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(testDbInfos)) {
            List<DataSourceEntity> ds = new ArrayList<>();
            for (TestDbInfo testDbInfo : testDbInfos) {
                DataSourceEntity sourceEntity = new DataSourceEntity();
                BeanUtils.copyProperties(testDbInfo,sourceEntity);
                sourceEntity.setKey(testDbInfo.getName());
                ds.add(sourceEntity);
            }
            dynamicDataSource.createDataSource(ds);
        }
    }
}
